<template>
  <el-row>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ name: 'dashboard' }">控制台</el-breadcrumb-item>
      <el-breadcrumb-item>订单</el-breadcrumb-item>
    </el-breadcrumb>

    <blank />

    <el-row>
      <el-col :span="24">
        <el-button type="text" class="del-selections" @click="delSelections()">删除选中项</el-button>
      </el-col>
    </el-row>

    <blank />

    <el-row>
      <el-table :data="orders" style="width: 100%" stripe @select-all="all" @select="select" v-loading="loading">
        <el-table-column type="selection" width="55"></el-table-column>
        
        <el-table-column type="expand">
          <template scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="OrderId">
                <span>{{ props.row.OrderId }}</span>
              </el-form-item>
              <el-form-item label="商品描述">
                <span>{{ props.row.Body }}</span>
              </el-form-item>
              <el-form-item label="商品详情">
                <span>{{ props.row.Detail }}</span>
              </el-form-item>
              <el-form-item label="附加数据">
                <span>{{ props.row.Attach }}</span>
              </el-form-item>
              <el-form-item label="商户订单Id">
                <span>{{ props.row.OutTradeNo }}</span>
              </el-form-item>
              <el-form-item label="订单总金额">
                <span>{{ props.row.TotalFee }}</span>
              </el-form-item>
              <el-form-item label="用户IP">
                <span>{{ props.row.SpbillCreateIp }}</span>
              </el-form-item>
              <el-form-item label="订单开始时间">
                <span>{{ props.row.OutTradeTimeStart }}</span>
              </el-form-item>
              <el-form-item label="OpenId">
                <span>{{ props.row.OpenId }}</span>
              </el-form-item>
              <el-form-item label="地址Id">
                <span>{{ props.row.AddressId }}</span>
              </el-form-item>
              <el-form-item label="保洁项">
                <span>{{ props.row.Item }}</span>
              </el-form-item>
              <el-form-item label="代金券">
                <span>{{ props.row.TicketId }}</span>
              </el-form-item>
              <el-form-item label="订单备注">
                <span>{{ props.row.desc }}</span>
              </el-form-item>
              <el-form-item label="性别">
                <span>{{ props.row.Sex }}</span>
              </el-form-item>
              <el-form-item label="地址详情">
                <span>{{ props.row.Addr }}</span>
              </el-form-item>
              <el-form-item label="备注">
                <span>{{ props.row.AddressMemo }}</span>
              </el-form-item>
              <el-form-item label="姓名">
                <span>{{ props.row.Name }}</span>
              </el-form-item>
              <el-form-item label="电话">
                <span>{{ props.row.Phone }}</span>
              </el-form-item>
              <el-form-item label="保洁需求">
                <span>{{ props.row.OrderDetail }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>

        <el-table-column label="姓名">
          <template scope="scope">
            <span>{{ scope.row.Name | name_sex(scope.row.Sex) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="Phone" label="电话" show-overflow-tooltip>
        </el-table-column>        

        <el-table-column label="预约时间">
          <template scope="scope">
            <span>{{ scope.row.ServiceTime | serviceTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="金额/元">
          <template scope="scope">
            <span>{{ scope.row.TotalFee | totalFee }}</span>
          </template>
        </el-table-column>

        <!--<el-table-column label="订单状态">
          <template scope="scope">
            <span style="font-weight: bold" :class="scope.row.State | OrderStateColor">{{ scope.row.State | OrderState }}</span>
          </template>
        </el-table-column>-->

        <el-table-column label="修改状态">
          <template scope="scope">
            <el-dropdown @command="updateState">
              <span class="el-dropdown-link" :class="scope.row.State | OrderStateColor">
                {{ scope.row.State | OrderState }}<i class="el-icon-caret-bottom el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="scope.$index.toString() + '_0'">待支付</el-dropdown-item>
                <el-dropdown-item :command="scope.$index.toString() + '_1'">进行中</el-dropdown-item>
                <el-dropdown-item :command="scope.$index.toString() + '_2'">已完成</el-dropdown-item>
                <el-dropdown-item :command="scope.$index.toString() + '_3'">已关闭</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>

        <el-table-column label="订单完成度">
          <template scope="scope">
            <span class="can-finish" :class="scope.row.CanFinish | canFinishColor" @click="setCanFinish(scope.$index.toString())">{{ scope.row.CanFinish | canFinish }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作">
          <template scope="scope">
            <span class="delete-order" @click="delOrders(scope.$index, scope.row)">删除</span>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <span class="change-state" :class="{ 'color-green': scope.row.IsHandled }" @click="changeOrderHandleState(scope.row)">{{ scope.row.IsHandled | isHandled }}</span>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <span class="refund" @click="requestRefund(scope.row)" v-if="!scope.row.IsRefund">退款</span>
            <span v-if="scope.row.IsRefund">已退款</span>
            &nbsp;&nbsp;&nbsp;&nbsp;
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <blank />

    <el-row>
      <el-col :span="24">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
  </el-row>
</template>

<script>
  import blank from '@/components/Blank'
  import { Message, MessageBox } from 'element-ui'
  import ax, { errhandler } from '@/api/_axios-config'
  import router from '@/router'
  import * as apis from '@/api/_api'

  export default {
    data () {
      return {
        currentPage: 1,
        pageSize: 20,
        total: 100,
        orders: [],
        deleteIds: [],
        pot: {},
        loading: true
      }
    },
    filters: {
      canFinishColor: function (canfinish) {
        if (canfinish) {
          return 'color-green'
        } else {
          return 'color-blue'
        }
      },
      canFinish: function (canfinish) {
        if (canfinish) {
          return '已完成'
        } else {
          return '进行中'
        }
      },
      isHandled: function (isread) {
        if (isread) {
          return '已阅'
        } else {
          return '未阅'
        }
      },
      isHandledColor: function (isread) {
        if (isread) {
          return 'success'
        } else {
          return 'warning'
        }
      },
      OrderState: function (state) {
        switch (state) {
          case -1: return '未知'
          case 0: return '未支付'
          case 1: return '进行中'
          case 2: return '已完成'
          case 3: return '已关闭'
          default: return '未知'
        }
      },
      OrderStateColor: function (state) {
        switch (state) {
          case -1: return 'color-black'
          case 0: return 'color-pink'
          case 1: return 'color-blue'
          case 2: return 'color-green'
          case 3: return 'color-gray'
          default: return 'color-black'
        }
      },
      cleaningTargetItem: function (item) {
        switch (item) {
          case 0: return '日常保洁'
          case 1: return '开荒保洁'
          case 2: return '玻璃清洗'
          case 3: return '地毯清洗'
          case 4: return '空调清洗'
          case 5: return '油烟机清洗'
          default: return '未知'
        }
      },
      totalFee: function (totalFee) {
        return totalFee / 100
      },
      name_sex: function (name, sex) {
        switch (sex) {
          case 0: return name + '来宾'
          case 1: return name + '先生'
          case 2: return name + '女士'
          default: return name + '来宾'
        }
      },
      serviceTime: function (time) {
        if (!time) {
          return '预约项'
        }
        var tm = time.split(',')[1]
        var dt = time.split(',')[0]
        if (tm === '1') {
          return dt + ' ' + '08:00-12:00'
        } else if (tm === '2') {
          return dt + ' ' + '13:30-17:30'
        } else {
          return dt + ' ' + '18:30-22:30'
        }
      }
    },
    name: 'order',
    components: { blank },
    methods: {
      updateState (cmd) {
        let temp = cmd.split('_')
        let index = temp[0]
        let state = temp[1]
        let id = this.orders[index]['OrderId']
        let openid = this.orders[index]['OpenId']

        ax.patch(apis.ORDERS_STATE_UPDATE, { id: id, state: state, openid: openid }).then(
          response => {
            let result = response.data
            if (result.BoolStatus) {
              this.orders[index]['State'] = parseInt(state)
              Message.success('修改状态成功')
            } else {
              Message.error(result.Message)
            }
          }
        ).catch(
          err => {
            errhandler(err)
          }
        )
      },
      requestRefund (row) {
        MessageBox.confirm('是否确定退款？一旦确定退款将直达对方账户，并且不可恢复，请谨慎操作。', '提示', {
          confirmButtonText: '退款',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          ax.get(apis.REFUND, { params: { outTradeNo: row.OutTradeNo } }).then(
            response => {
              let result = response.data
              if (result.state === 'SUCCESS') {
                Message.success('退款已经成功')
              } else {
                Message.error(result.errmsg)
              }
            }
          ).catch(
            err => {
              errhandler(err)
            }
          )
        }).catch(() => {
          Message.info('取消退款操作')
        })
      },
      handleSizeChange (size) {
        this.pageSize = size
        this.getOrdersData(this.pageSize, this.currentPage)
      },
      handleCurrentChange (page) {
        this.currentPage = page
        this.getOrdersData(this.pageSize, this.currentPage)
      },
      selectHandle (selections) {
        let ids = []
        selections.forEach(function (item) {
          ids.push(item.OrderId)
        })
        this.deleteIds = ids
      },
      all (selections) {
        this.selectHandle(selections)
      },
      select (selections, row) {
        this.selectHandle(selections)
      },
      changeOrderHandleState (row) {
        ax.patch(apis.ORDERHANDLESTATE, { handleState: !row.IsHandled, id: row.OrderId }).then(
          response => {
            let result = response.data
            if (result.BoolStatus) {
              Message.success('修改状态成功')
              row.IsHandled = !row.IsHandled
            } else {
              Message.error(response.Message)
            }
          }
        ).catch(
          err => {
            errhandler(err)
          }
        )
      },
      getOrdersData (pageSize, page) {
        this.loading = true
        ax.get(apis.ORDERS, { params: { pageSize: pageSize, page: page } }).then(
          response => {
            let result = response.data
            if (result.BoolStatus) {
              this.orders = result.Data.data
              this.total = result.Data.totalCount
            } else {
              Message.info('未获取订单信息')
            }
            this.loading = false
          }
        ).catch(
          err => {
            errhandler(err)
            this.loading = false
          }
        )
      },
      delOrders (index, row) {
        MessageBox.confirm('确定删除该订单？此操作不可恢复数据', '提示', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          let ids = [ row.OrderId ]
          ax.delete(apis.ORDERS_DELETE, { data: ids }).then(
            response => {
              var result = response.data
              if (result.BoolStatus) {
                this.orders.splice(index, 1)
                Message.success('删除成功')
              } else {
                Message.success('删除失败')
              }
            }
          ).catch(
            err => {
              errhandler(err)
            }
          )
        }).catch(() => {
          Message.info('取消删除操作')
        })
      },
      delSelections () {
        if (this.deleteIds === [] || this.deleteIds.length <= 0) {
          Message.info('未选中任何元素')
          return
        }
        MessageBox.confirm('确定删除选中的订单？此操作不可恢复数据', '提示', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          ax.delete(apis.ORDERS_DELETE, { data: this.deleteIds }).then(
            response => {
              var result = response.data
              if (result.BoolStatus) {
                Message.success('删除成功')
                router.go(0)
              } else {
                Message.success('删除失败')
              }
            }
          ).catch(
            err => {
              errhandler(err)
            }
          )
        }).catch(() => {
          Message.info('取消删除操作')
        })
      },
      setPOT () {
        ax.get(apis.POT).then(
          response => {
            let result = response.data
            if (result.BoolStatus) {
              this.pot = result.Data
            } else {
              Message.error('获取下单配置失败')
            }
            window.localStorage.setItem('pot', JSON.stringify(this.pot))
          }
        ).catch(
          err => {
            errhandler(err)
          }
        )
      },
      setCanFinish (index) {
        let row = this.orders[index]
        ax.patch(apis.UPDATE_CAN_FINISH, { id: row.OrderId, canFinish: !row.CanFinish }).then(
          response => {
            let result = response.data
            if (result.BoolStatus) {
              this.orders[index]['CanFinish'] = !row.CanFinish
              Message.success('修改状态成功')
            } else {
              Message.success(result.Message)
            }
          }
        ).catch(
          err => {
            errhandler(err)
          }
        )
      }
    },
    created: function () {
      this.getOrdersData(this.pageSize, this.currentPage)
      this.setPOT()
    }
  }
</script>

<style lang="stylus">
  .del-selections
    font-weight bold
    cursor pointer
    color #FF4949

  .demo-table-expand
    font-size 0
  
  .demo-table-expand label
    width 100px
    color #99a9bf
    font-weight bold
  
  .demo-table-expand .el-form-item
    margin-right 0
    margin-bottom 0
    width 50%

  .change-state
    color #993399
    font-weight bold
    cursor pointer

  .color-green
    color #13CE66
  
  .color-pink
    color #FF3399

  .color-gray
    color #999999

  .color-blue
    color #0099CC
    font-weight bold

  .color-black
    color #000000

  .delete-order
    color red
    font-weight bold
    cursor pointer

  .el-dropdown-link
    cursor pointer

  .refund
    cursor pointer
    color gray
    font-weight bold

  .can-finish
    cursor pointer
    font-weight bold
</style>
